﻿using System;
using System.Windows.Forms;
using Relocation.Data;
using Relocation.Base;
using Relocation.Com;
using Relocation.Com.Tools;
using Relocation.Base.UI;
using System.Linq;

namespace Relocation
{
	public partial class UserWindow : BaseForm
	{

		public User User;

		public UserWindow()
			: base()
		{
			Initialize();
		}

		public UserWindow(Session session)
			: base(session)
		{
			Initialize();
		}

		private void Initialize()
		{
			InitializeComponent();
			this.password.Tag = new ControlTag(User.GetPropName(t => t.password), new ValidatorInfo(new ValidatorInfo.ValidatorHandler(delegate(Control control) {
				control.Text = control.Text.Trim();
				int count=control.Text.Length;
				bool result=count < 12 && count > 6;
				return new ValidatorInfo.ValidatorResult(result, result ? string.Empty : "密码长度只能在6-12位之间！");
			})));
			this.username.Tag = new ControlTag(User.GetPropName(t => t.name), new ValidatorInfo(new ValidatorInfo.ValidatorHandler(delegate(Control control) {
				string value = control.Text;
				if (String.IsNullOrEmpty(value))
				{
					return new ValidatorInfo.ValidatorResult(false, "用户名必须填写");
				}
				int userId = this.Session.DataModel.User.Where(t => t.name.Equals(value)).Select(t => t.userID).FirstOrDefault();
				if (userId == 0)
					return new ValidatorInfo.ValidatorResult(true);
				if (this.User != null && this.User.userID == userId)
					return new ValidatorInfo.ValidatorResult(true);
				else
					return new ValidatorInfo.ValidatorResult(false, "用户名已经存在");

			})));
			this.save.Tag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN));
		}

		public UserWindow(Session session, User user):this(session)
		{
			this.User = user;			
			this.username.Text = user.name;
			this.password.Text = user.password;
			this.enable.Checked = user.enable.HasValue ? user.enable.Value : false;
			this.role.Text = User.role.Equals("admin") ? "管理员" : User.role.Equals("operator") ? "操作员" : "普通用户";			
			this.FieldIsChanged = false;
		}

		private void save_Click(object sender, EventArgs e)
		{
			try
			{
				if (!this.ValidatorAllControls())
					return;

				if (this.User == null)
				{
					this.User = new User();
					User.created = DateTime.Now;
				}
				User.name = this.username.Text;
				User.password = this.password.Text;
				User.enable=this.enable.Checked;				
				this.User.role = this.role.Text.Equals("管理员") ? "admin" : this.role.Text.Equals("操作员") ? "operator" : "general";
				User.updated = DateTime.Now;
				this.Session.DataModel.Save(User);
				
				this.FieldIsChanged = false;
				this.DialogResult = DialogResult.OK;
				this.Close();
			} catch (Exception ex)
			{				
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("操作失败！");
			}
		}
	
	}
}
